package middleware

import (
	"github.com/goflyfox/gtoken/gtoken"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/model"
	"lot_admin_api/internal/service"
	"lot_admin_api/utility/response"
)

// OperateGfToken Operate_token中间件
func OperateGfToken() (res *gtoken.GfToken) {
	res = &gtoken.GfToken{
		LoginPath:        "/user/login",
		LoginBeforeFunc:  JwtOperateLogin,
		LoginAfterFunc:   LoginAfterFunc,
		LogoutAfterFunc:  LogoutAfterFunc,
		LogoutPath:       "/user/logout",
		CacheMode:        2,
		AuthExcludePaths: g.SliceStr{"/operate/third-party/*"}, // 不拦截路径
		MultiLogin:       false,
		CacheKey:         "GTokenOperate:",
	}
	return res
}

// JwtOperateLogin  运营端登录验证
func JwtOperateLogin(r *ghttp.Request) (string, interface{}) {
	var req *model.LoginStruct
	ctx := r.Context()
	// 校验
	if err := r.Parse(&req); err != nil {
		response.JsonExit(r, consts.HTTPBadRequest.Code(), err.Error())
	}
	// 请求登录函数 , 里面的type 来判断是哪一种登录
	result, _ := service.Operate().Login(ctx, req)
	return result.OperatePhone, result
}

// LoginAfterFunc 登录完成后的操作
func LoginAfterFunc(r *ghttp.Request, respData gtoken.Resp) {
	if respData.Code == 0 {
		response.JsonExit(r, consts.HTTPSuccess.Code(), "登录成功", respData.Data)
	}
	if respData.Code == -1 {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "登录失败", respData.Msg)
	}
	if respData.Code == -99 {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "token认证错误", respData.Msg)
	}
	if respData.Code == -401 {
		response.JsonExit(r, consts.HTTPUnauthorized.Code(), consts.HTTPUnauthorized.Message(), respData.Msg)
	}
}

// LogoutAfterFunc 登出完成后的操作
func LogoutAfterFunc(r *ghttp.Request, respData gtoken.Resp) {
	if respData.Code != 0 {
		response.JsonExit(r, consts.HTTPSuccess.Code(), respData.Msg, respData.Data)
	} else {
		response.JsonExit(r, consts.HTTPSuccess.Code(), "登出成功", respData.Data)
	}
}
